<?php

namespace Api\Controller;

/**
 * 文艺在线
 *
 * Class NewsController
 * @package Api\Controller
 */
class NewsController extends PublicController
{
    private $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = M('News');
    }

    /**
     * 获取文艺在线分页数据
     */
    public function getList()
    {
        $perPage = !empty($_GET['per_page']) ? intval($_GET['per_page']) : 10;
        $curPage = !empty($_GET['page']) ? intval($_GET['page']) : 1;
        $where = "is_del=0";
        $count = $this->model->where($where)->count();
        $totalPage = ceil($count / $perPage);
        $list = $this->model->where($where)->field('id,title,cover,video,create_at,zan,comments,sort')->order('sort = 0, sort asc, id desc')->limit(($curPage - 1) * $perPage, $perPage)->select();
        foreach ($list as $k => $v) {
            $list[$k]['cover'] = __DATAURL__ . $v['cover'];
            $list[$k]['create_at'] = date('Y-m-d', strtotime($v['create_at']));
        }

        $this->json_result([
            'per_page'   => $perPage,
            'total'      => $count,
            'total_page' => $totalPage,
            'cur_page'   => $curPage,
            'list'       => $list,
        ]);
    }

    /**
     * 获取文艺在线详情
     */
    public function detail()
    {
        $userId = intval($this->get("id"));

        if (!$userId) {
            $this->json_error("请登录");
        }

        $id = intval($_REQUEST['id']);
        $detail = $this->model->where(['id' => $id, 'is_del' => 0])->find();
        if (!$detail) {
            $this->json_error('没有找到相关信息');
        }

        $detail['content'] = str_replace(['../../../Data/', "/Data/"], ['/Data/', __DATAURL__], $detail['content']);
        $detail['cover'] = __DATAURL__ . $detail['cover'];

        $zan = M('zan')->where(['user_id' => $userId, 'object_type' => 1, 'object_id' => $id])->find();
        $detail['my_zan'] = $zan ? 1 : 0;

        $this->json_result($detail);
    }
}